package com.quectel.core.module.dept.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dao.DeptPersonDao;
import com.quectel.core.module.dept.dto.DeptDto;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.dto.DeptPersonRoleDto;
import com.quectel.core.module.dept.dto.DeptPersonRoleRelationDto;
import com.quectel.core.module.dept.entity.DeptPersonEntity;
import com.quectel.core.module.dept.service.DeptPersonRoleRelationService;
import com.quectel.core.module.dept.service.DeptPersonRoleService;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.dept.service.DeptService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/03/24 10:07
 */
@DubboService
public class DeptPersonServiceImpl implements DeptPersonService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeptPersonServiceImpl.class);

    private static final String DEPT_PERSON_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "DEPT_PERSON_CACHE_BY_ID:";

    @Autowired
    private VillageService villageService;
    @Autowired
    private DeptPersonDao deptPersonDao;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DeptPersonRoleService deptPersonRoleService;
    @Autowired
    private DeptPersonRoleRelationService deptPersonRoleRelationService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRoleRelation(DeptPersonDto dto) {
        deptPersonRoleRelationService.deleteByPersonId(dto.getId());
        if (CollectionUtils.isEmpty(dto.getDeptPersonRoleDtos())) {
            return;
        }
        for (DeptPersonRoleDto deptPersonRoleDto : dto.getDeptPersonRoleDtos()) {
            DeptPersonRoleRelationDto deptPersonRoleRelationDto = new DeptPersonRoleRelationDto();
            deptPersonRoleRelationDto.setDeptRoleId(deptPersonRoleDto.getId());
            deptPersonRoleRelationDto.setDeptPersonId(dto.getId());
            deptPersonRoleRelationService.save(deptPersonRoleRelationDto);
        }
    }


    @Override
    public List<DeptPersonDto> selectByDeptId(Long deptId) {
        List<DeptPersonEntity> deptPersonEntities = deptPersonDao.selectList(new LambdaQueryWrapper<DeptPersonEntity>().eq(DeptPersonEntity::getDeptId, deptId));
        return CopyUtils.copyList(deptPersonEntities, DeptPersonDto.class);
    }

    @Override
    public DeptPersonDto selectByVillageAndMobile(Long villageId, String mobile) {
        DeptPersonEntity entity = deptPersonDao.selectOne(new LambdaQueryWrapper<DeptPersonEntity>()
                .eq(DeptPersonEntity::getVillageId, villageId)
                .eq(DeptPersonEntity::getMobile, mobile)
                .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        return paddingField(CopyUtils.copyObj(entity, DeptPersonDto.class));
    }

    @Override
    public DeptPersonDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEPT_PERSON_CACHE_BY_ID + id,
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DeptPersonDto selectById(Long id) {
        DeptPersonEntity entity = deptPersonDao.selectById(id);
        DeptPersonDto deptPersonDto = paddingField(CopyUtils.copyObj(entity, DeptPersonDto.class));

        if (deptPersonDto != null) {
            List<DeptPersonRoleDto> deptPersonRoleDtos = deptPersonRoleService.selectRoleByPersonId(id);
            deptPersonDto.setDeptPersonRoleDtos(deptPersonRoleDtos);
        }

        return deptPersonDto;
    }

    @Override
    public List<DeptPersonDto> queryList(Map<String, Object> params) {
        if (params.containsKey("parentDeptId")
                && NumberUtils.isDigits(params.get("parentDeptId") + "")) {
            Long deptId = Long.valueOf(params.get("parentDeptId") + "");
            List<DeptDto> allDept = deptService.queryByRecursion(deptId);
            params.put("deptIds", allDept.stream().map(DeptDto::getId).toArray(Long[]::new));
        }
        List<DeptPersonEntity> list = deptPersonDao.queryList(params);
        List<DeptPersonDto> result = CopyUtils.copyList(list, DeptPersonDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private DeptPersonDto paddingField(DeptPersonDto dto) {
        if (dto != null) {
            DeptDto deptDto = deptService.selectCacheById(dto.getDeptId());
            dto.setDept(deptDto);

            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            if (villageDto != null) {
                dto.setVillageName(villageDto.getName());
            }
        }
        return dto;
    }


    @Override
    public int queryTotal(Map<String, Object> params) {
        return deptPersonDao.queryTotal(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(DeptPersonDto dto) {
        DeptPersonEntity entity = CopyUtils.copyObj(dto, DeptPersonEntity.class);
        entity.setId(Snowflake.nextId());
        deptPersonDao.insert(entity);

        saveUserRoleRelation(dto);

        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DeptPersonDto dto) {
        DeptPersonEntity entity = CopyUtils.copyObj(dto, DeptPersonEntity.class);
        deptPersonDao.updateById(entity);

        saveUserRoleRelation(dto);

        CacheKit.invalidRedisCache(DEPT_PERSON_CACHE_BY_ID + dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAllColumnById(DeptPersonDto dto) {
        DeptPersonEntity entity = CopyUtils.copyObj(dto, DeptPersonEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, deptPersonDao);

        saveUserRoleRelation(dto);

        CacheKit.invalidRedisCache(DEPT_PERSON_CACHE_BY_ID + dto.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        deptPersonDao.deleteById(id);

        deptPersonRoleRelationService.deleteByPersonId(id);
        CacheKit.invalidRedisCache(DEPT_PERSON_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
